package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.commom.constants.articlle.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.wemedia.WmMaterialConstant;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private AdminFeign adminFeign;
    @Autowired
    private AuthorMapper authorMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    GeneratePageService generatePageService;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Value("${file.minio.readPath}")
    private String readPath;

    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 100000)
    @Override
    public void publishArticle(Integer newsId) {
        //查询并检查自媒体文章状态
        WmNews wmNews = getWmNews(newsId);
        //将文章信息 copy到ApArticle中
        ApArticle apArticle = getApArticle(wmNews);
       //保存或修改 article信息
        saveOrUpdateArticle(apArticle);
        //保存关联配置和内容信息
        saveConfigAndContent(wmNews,apArticle);
        //更新wmNews状态 修改为已发布9 并设置articleId
        updateWmNews(newsId,wmNews,apArticle);

        generatePageService.generateArticlePage(wmNews.getContent(),apArticle);
    }

   //修改自媒体文章
    private void updateWmNews(Integer newsId, WmNews wmNews, ApArticle apArticle) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(apArticle.getId());
        ResponseResult<WmNews> result = wemediaFeign.updateWmNews(wmNews);
        if(!result.checkCode()){
            log.error("远程调用修改文章失败  文章发布失败  文章id:{}",newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
    }

    //保存关联配置 和内容信息
    private void saveConfigAndContent(WmNews wmNews, ApArticle apArticle) {
        //添加配置信息
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfigMapper.insert(apArticleConfig);

        //添加内容信息
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        apArticleContentMapper.insert(apArticleContent);


    }

    //保存或修改 article信息
    private void saveOrUpdateArticle(ApArticle apArticle) {
        //判断wmNews之前是否关联 articleId 有关联 就是修改 无关联 就是保存 新增
        if(apArticle.getId() == null){
            //无关联 保存文章信息
            apArticle.setCollection(0); //收藏数
            apArticle.setLikes(0);      //点赞数
            apArticle.setComment(0);    //评论数
            apArticle.setViews(0);      //阅读数
            save(apArticle);
        }else {
            // 修改信息   先删除掉关联的配置信息
            ApArticle article = getById(apArticle.getId());
            if(article == null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的文章不存在");
            }
            updateById(apArticle);
            //删除文章配置关联
            apArticleConfigMapper.delete
                    (Wrappers.<ApArticleConfig>lambdaQuery()
                            .eq(ApArticleConfig::getArticleId,apArticle.getId()));
            //删除文章内容关联
            apArticleContentMapper.delete
                    (Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,apArticle.getId()));

        }
    }

    // 封装 文章信息到ApArticle中
    private ApArticle getApArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(wmNews,apArticle);
        apArticle.setId(wmNews.getArticleId());
        apArticle.setFlag((byte)0);
        apArticle.setLayout(wmNews.getType());

        //远程查询频道信息
        ResponseResult<AdChannel> result = adminFeign.findOne(wmNews.getChannelId());
        if(!result.checkCode()){
            log.error("远程调用 查询频道信息出错了  文章发布失败 文章id :{} 频道id {}",wmNews.getId(),wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"查询频道信息时出错");
        }
        AdChannel adChannel = result.getData();
        if(adChannel == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST ,"未查询到频道信息");
        }
        //设置频道名称
        apArticle.setChannelName(adChannel.getName());

        //查询作者信息
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery()
                .eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if(apAuthor == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"查询作者信息失败 未查询到");
        }
        apArticle.setAuthorId(apAuthor.getId().longValue());
        apArticle.setAuthorName(apAuthor.getName());
        return apArticle;
    }

    //查询自媒体文章
    private WmNews getWmNews(Integer newsId) {
        ResponseResult<WmNews> result = wemediaFeign.findWmNewsById(newsId);
        if (!result.checkCode()) {
            log.info("根据id查询文章远程调用feign 出错了 newsId为:{}",newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmNews wmNews = result.getData();
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在 ");
        }
        //判断文章状态 是否为以过审 4 人工审核通过 8 自动审核通过
        Short status = wmNews.getStatus();
        if(status != WmNews.Status.ADMIN_SUCCESS.getCode() && status != WmNews.Status.SUCCESS.getCode()){
            log.info("文章处于未过审 状态 不可发布文章 文章id为:{}",newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章状态未过审 不可发布");
        }
        return wmNews;
    }

    /**
     * 根据参数查询文章列表
     * @param type 0 加载更多 1 加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short type, ArticleHomeDTO dto) {

        //因为 当前操作时展示给用户的所以尽量不抛出异常  而是 给为空的参数 设置一个默认值
        //获取页大小  如果小于等于0 就查询是条数据
        Integer size = dto.getSize();
        if(size <= 0 || size == null){
            size = 10;
        }
        //根据频道获取信息  如果频道为空的话 查询所有
        if(StringUtils.isBlank(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //设置最大时间 和最小时间
        if(dto.getMinBehotTime() == null){
            dto.setMinBehotTime(new Date());
        }
        if(dto.getMaxBehotTime() == null){
            dto.setMaxBehotTime(new Date());
        }
        //设置type 参数
        if(!type .equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !type.equals(ArticleConstants.LOADTYPE_LOAD_NEW)){
            type=ArticleConstants.LOADTYPE_LOAD_MORE;
        }

        //执行查询
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, type);
        //将查询的结果中 封面 做处理
        //有些文章可能会存在没有图片的情况 纯文本 那么这些就不用进行设置封面路径
        for (ApArticle apArticle : apArticles) {
            //获取封面路径
            String images = apArticle.getImages();
            if(StringUtils.isNotBlank(images)){
                images = Arrays.stream(images.split(","))
                        .map(url -> webSite + url)
                        .collect(Collectors.joining(","));
                apArticle.setImages(images);
            }
            apArticle.setStaticUrl(readPath+apArticle.getStaticUrl());
        }

        return ResponseResult.okResult(apArticles);
    }


}